package com.fantasy.blog.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fantasy.blog.dao.dos.Archives;
import com.fantasy.blog.dao.mapper.ArticleBodyMapper;
import com.fantasy.blog.dao.mapper.ArticleMapper;
import com.fantasy.blog.dao.mapper.ArticleTagMapper;
import com.fantasy.blog.dao.mapper.TagMapper;
import com.fantasy.blog.dao.pojo.Article;
import com.fantasy.blog.dao.pojo.ArticleBody;
import com.fantasy.blog.dao.pojo.ArticleTag;
import com.fantasy.blog.dao.pojo.SysUser;
import com.fantasy.blog.service.*;
import com.fantasy.blog.utils.UserThreadLocal;
import com.fantasy.blog.vo.ArticleBodyVo;
import com.fantasy.blog.vo.ArticleVo;
import com.fantasy.blog.vo.Result;
import com.fantasy.blog.vo.TagVo;
import com.fantasy.blog.vo.params.ArticleParam;
import com.fantasy.blog.vo.params.PageParams;
import org.joda.time.DateTime;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class ArticleServiceImpl implements ArticleService {

    @Autowired
    private ArticleMapper articleMapper;
    @Autowired
    private TagService tagService;
    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private ArticleTagMapper articleTagMapper;
    @Autowired
    private ArticleBodyMapper articleBodyMapper;

    @Override
    public Result listArticle(PageParams pageParams) {
        Page<Article> page = new Page<>(pageParams.getPage(), pageParams.getPageSize());
        IPage<Article> articleIPage = articleMapper.listArticle(page,
                pageParams.getCategoryId(),
                pageParams.getTagId(),
                pageParams.getYear(),
                pageParams.getMonth());

        List<Article> records = articleIPage.getRecords();
        return Result.success(copyList(records,true,true));

    }

    @Override
    public Result hotArticle(int limit) {
        LambdaQueryWrapper<Article> queryWrapper = new LambdaQueryWrapper();
        queryWrapper
                .orderByDesc(Article::getViewCounts)
                .select(Article::getId,Article::getTitle)
                .last("limit " + limit)
        ;
        //select id,title from ms_article order by view_count desc limit 5
        List<Article> articles = articleMapper.selectList(queryWrapper);
        return Result.success(copyList(articles,false,false));
    }

    @Override
    public Result newArticle(int limit) {
        LambdaQueryWrapper<Article> queryWrapper = new LambdaQueryWrapper();
        queryWrapper
                .orderByDesc(Article::getCreateDate)
                .select(Article::getId,Article::getTitle)
                .last("limit " + limit)
        ;
        //select id,title from ms_article order by create_date desc limit 5
        List<Article> articles = articleMapper.selectList(queryWrapper);
        return Result.success(copyList(articles,false,false));
    }

    @Override
    public Result listArchives() {
        List<Archives> archivesList = articleMapper.listArchives();
        return Result.success(archivesList);
    }

    @Autowired
    private ThreadService threadService;

    @Override
    public Result findArticleById(Long articleId) {
        /**
         * 1.根据id查询
         * 2.根据bodyID查内容
         * 3.根据标签Id查标签
         */
        Article article = articleMapper.selectById(articleId);
        ArticleVo articleVo = copy(article,true,true,true,true);
        /**
         * 采用线程池来更新阅读数
         * 异步更新阅读数量，提升效率
         *
         * 也可采用redis来实现
         */
        threadService.updateArticleViewCount(articleMapper,article);
        return Result.success(articleVo);
    }

    @Override
    public Result publish(ArticleParam articleParam) {
        Article article = new Article();
        SysUser sysUser = UserThreadLocal.get();
        article.setId(articleParam.getId());
        article.setAuthorId(sysUser.getId());
        article.setCreateDate(System.currentTimeMillis());
        article.setTitle(articleParam.getTitle());
        article.setSummary(articleParam.getSummary());
        article.setCategoryId(articleParam.getCategory().getId());
        article.setDisplayImg(articleParam.getDisplayImg());
        article.setWeight(articleParam.getWeight());
        Long articleId = articleParam.getId();
        ArticleBody articleBody = new ArticleBody();
        articleBody.setContent(articleParam.getBody().getContent());
        articleBody.setContentHtml(articleParam.getBody().getContentHtml());
        if(null==article.getId()){
            article.setViewCounts(0);
            article.setCommentCounts(0);
            articleMapper.insert(article);
            articleId = article.getId();
            articleBody.setArticleId(articleId);
            articleBodyMapper.insert(articleBody);
        }else {
            LambdaQueryWrapper<ArticleTag> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(ArticleTag::getArticleId,article.getId());
            articleTagMapper.delete(queryWrapper);
            LambdaQueryWrapper<ArticleBody> queryWrapper2 = new LambdaQueryWrapper<>();
            queryWrapper2.eq(ArticleBody::getArticleId,articleId);
            articleBodyMapper.update(articleBody,queryWrapper2);
        }
        List<TagVo> tags = articleParam.getTags();
        if(null != tags){
            for (TagVo tag : tags) {
                ArticleTag articleTag = new ArticleTag();
                articleTag.setTagId(tag.getId());
                articleTag.setArticleId(articleId);
                articleTagMapper.insert(articleTag);
            }
        }
        article.setBodyId(articleBody.getId());
        articleMapper.updateById(article);

        Map<String,String> map = new HashMap<>();
        map.put("id",articleId.toString());
        return Result.success(map);
    }

    @Override
    public Result delByArticleId(Long articleId) {
        articleMapper.deleteById(articleId);
        LambdaQueryWrapper<ArticleBody> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ArticleBody::getArticleId,articleId);
        articleBodyMapper.delete(queryWrapper);
        tagService.delTagsByArticleId(articleId);
        return Result.success("删除成功");
    }


    private List<ArticleVo> copyList(List<Article> records,boolean isTag,boolean isAuthor) {
        List<ArticleVo> articleVoList = new ArrayList<>();
        for(Article record:records){
            articleVoList.add(copy(record,isTag,isAuthor,false,false));
        }
        return articleVoList;
    }

    private List<ArticleVo> copyList(List<Article> records,boolean isTag,boolean isAuthor,boolean isBody,boolean isCategory) {
        List<ArticleVo> articleVoList = new ArrayList<>();
        for(Article record:records){
            articleVoList.add(copy(record,isTag,isAuthor,isBody,isCategory));
        }
        return articleVoList;
    }

    private ArticleVo copy(Article article,boolean isTag,boolean isAuthor,boolean isBody,boolean isCategory){
        ArticleVo articleVo = new ArticleVo();
        BeanUtils.copyProperties(article,articleVo);
        articleVo.setCreateDate(new DateTime(article.getCreateDate()).toString("yyyy-MM-dd HH:mm"));
        if(isTag){
            Long id = article.getId();
            articleVo.setTags(tagService.findTagsByArticleId(id));
        }
        if(isAuthor){
            Long authorId = article.getAuthorId();
            articleVo.setAuthor(sysUserService.findUserById(authorId).getNickname());
        }
        if(isBody){
            Long bodyId = article.getBodyId();
            articleVo.setBody(findArticleBodyByBodyId(bodyId));
        }
        if(isCategory){
            Long categoryId = article.getCategoryId();
            articleVo.setCategory(categoryService.findCategoryById(categoryId));
        }
        return articleVo;
    }

    private ArticleBodyVo findArticleBodyByBodyId(Long bodyId) {
        ArticleBody articleBody = articleBodyMapper.selectById(bodyId);
        ArticleBodyVo articleBodyVo = new ArticleBodyVo();
        articleBodyVo.setContent(articleBody.getContent());
        return articleBodyVo;
    }
}
